package com.compass.mobile.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentCaseItemBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.BASE_PDF
import com.compass.mobile.framework.constant.CLOUD_FILM_URL
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.InspectionReport
import com.compass.mobile.presenters.NuclearMedicineReportPresenter
import com.compass.mobile.ui.activity.WebDetailActivity
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.viewModel.ReportViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import java.net.URLDecoder

/**
 * Description： 核医学报告
 * Date:2024/6/29 15:19
 */
class NuclearMedicineReportFragment : BaseVBFragment<FragmentCaseItemBinding>() {
    private val reportViewModel: ReportViewModel by viewModels()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var reportList: MutableList<InspectionReport> = mutableListOf()

    private var reportType: String = "NUCLEAR"
    private var type: String = "0"
    private var startDate: Long? = null
    private var endDate: Long? = null
    override fun initView(view: View, savedInstanceState: Bundle?) {
        specialColumn()
        mBinding?.llBelow?.gone()

    }

    override fun initData() {
//        var patientId = "1788357171355537409" //测试患者
        var patientId= UserInfoManager.getPatientInfo()?.id
        startDate = DateUtils.yearMonthDayToTimestamp(2018, 1, 1)
        reportViewModel.geReportList(patientId, type, reportType, startDate, DateUtils.getToday() )
        reportViewModel.reportListLiveData.observe(this) {
            dismissLoading()

            if (it.isNullOrEmpty()) {
                mBinding?.emptyView?.visible()
                mBinding?.llBelow?.gone()
            } else {

                mBinding?.emptyView?.gone()
                reportList = it

                arrayObjectAdapter.addAll(0, reportList)
            }

        }

    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = reportList[position]
            when (reportType) {
                "LIS" -> {
                    openPDF(item.pdfUrl)
                }

                "PACS" -> {
                    if (isShowCloudFilm(item.reportName)) {
                        openFilm(item)
                    } else {
                        openPDF(item.pdfUrl)
                    }

                }
            }


        }
    }


    private fun openPDF(pdfUrl: String) {
//        WebDetailActivity.start(
//            requireContext(),
//            BASE_PDF + URLDecoder.decode(pdfUrl, "utf-8"),
//            "报告单"
//        )
        val oderCodeDialog =
            CodeDialog.Builder(requireActivity(), BASE_PDF + URLDecoder.decode(pdfUrl, "utf-8"))
        oderCodeDialog.show()
    }

    private fun openFilm(item: InspectionReport) {
        //云胶片配置地址
        UserInfoManager.getString(CLOUD_FILM_URL)?.let { basUrl ->
            var url =
                "${basUrl}?type=0&patientid=${item.patientId}&acessionno=${item.reportNumber}"
            val oderCodeDialog =
                CodeDialog.Builder(requireActivity(), url)
            oderCodeDialog.show()
        } ?: kotlin.run {
            showToast("云胶片地址异常")
        }
    }

    private fun isShowCloudFilm(reportName: String?): Boolean {
        reportName?.let {
            return (it.contains("数字化摄影（DR）") || it.contains("CT") || it.contains(
                "1.5T MR"
            )
                    || it.contains("3.0T MR") || it.contains("数字胃肠") || it.contains(
                "乳腺X线摄影"
            ))
        } ?: kotlin.run {
            return false
        }

    }


    @SuppressLint("RestrictedApi")
    fun specialColumn() {

        mBinding?.caseItem?.horizontalSpacing = dpToPx(10)
        mBinding?.caseItem?.verticalSpacing = dpToPx(10)

        arrayObjectAdapter = ArrayObjectAdapter(NuclearMedicineReportPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )

        mBinding?.caseItem?.setAdapter(itemBridgeAdapter)
        mBinding?.caseItem?.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, reportList)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
    }
}
